<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>HKXDR</title>
    <meta name="renderer" content="webkit" />
    <link rel="stylesheet" href="res/layui/css/layui.css" />
    <style>
      @charset 'utf-8';

      @font-face {
        font-family: SourceHanSansCN-Regular;
        src: url("res/css/SourceHanSansCN-Regular.otf");
      }

      body {
        overflow-x: hidden;
      }

      /* c++弹框头部 */
      .popup-header {
        height: 40px;
        background: #4b6eef;
        box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.05);
      }

      /* 整体布局 start */
      .register {
        font-family: SourceHanSansCN-Regular;
        padding-top: 16px;
        width: 530px;
        margin: 0 auto;
        border: 1px solid #4b6eef;
        border-top: none;
        height: 330px;
        box-sizing: border-box;
      }

      .register.online-type {
        width: 480px;
        height: 235px;
      }
      /* 整体布局 end */

      /* input 三态 start */
      .layui-input:hover,
      .layui-textarea:hover {
        border-color: #4b6eef !important;
      }

      .layui-input:focus,
      .layui-textarea:focus {
        border-color: #4b6eef !important;
        box-shadow: 0 0 0 2px rgba(75, 110, 239, 0.3);
      }

      .layui-input {
        height: 32px;
        line-height: 32px;
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        color: #606266;
      }
      /* input 三态 end */

      /* 表单 start */
      .layui-input-block {
        width: 240px;
        position: relative;
        margin-left: 122px;
      }

      #deviceId {
        line-height: 31px;
      }

      .upload-block {
        width: 332px;
        color: #484848;
      }

      .upload-part {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        cursor: default;
      }

      .upload-part .layui-input {
        width: 240px;
        margin-right: 17px;
      }

      .layui-input-block .layui-icon-down {
        position: absolute;
        right: 10px;
        top: 10px;
        color: #888888;
        font-size: 12px;
      }

      .register .layui-input:focus {
        border-radius: 4px;
        border: 1px solid rgba(75, 110, 239, 1) !important;
        box-shadow: 0 0 0 2px rgba(75, 110, 239, 0.3);
        border-radius: 4px;
      }

      .layui-form-item {
        margin-top: 15px;
        margin-bottom: 15px;
        margin-left: 40px;
      }

      .online-type .layui-form-item {
        margin-top: 20px;
        margin-bottom: 20px;
        margin-left: 40px;
      }

      .submit-item {
        margin: 11px 0 0;
      }

      .layui-form-label {
        width: 108px;
        padding: 0 7px;
        line-height: 30px;
        font-size: 14px;
        color: #555555;
      }

      .layui-form-label::before {
        content: "*";
        color: red;
      }
      /* 表单 end */

      .error-info {
        display: none;
      }

      .error-key {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        margin: 6px 0;
        margin-bottom: 0;
        font-family: SourceHanSansCN-Regular;
        font-size: 14px;
        color: #ff3535;
        line-height: 1;
        font-weight: 400;
      }

      .icon {
        width: 16px;
      }

      .submit-box {
        margin-top: 40px;
        text-align: center;
      }

      .submit-box .layui-btn {
        font-family: SourceHanSansCN-Regular;
        height: 34px;
        width: 104px;
        line-height: 34px;
        background: #4b6eef;
        border-radius: 4px;
        font-size: 14px;
        color: #ffffff;
      }

      .submit-box .layui-btn:hover {
        background: #6383fb;
        font-family: SourceHanSansCN-Regular;
        font-size: 14px;
        color: #ffffff;
        letter-spacing: 0;
        text-align: center;
        font-weight: 400;
      }

      /* 下拉选择树 start*/
      .one-tree-select {
        width: 240px;
        position: relative;
        font-size: 14px;
        color: #606266;
      }

      /* select触发主体 */
      .one-selected {
        background-color: #fff;
        background-image: none;
        border-radius: 4px;
        border: 1px solid rgba(0, 0, 0, 0.15);
        color: #606266;
        /* font-size: inherit; */
        height: 32px;
        line-height: 32px;
        outline: none;
        padding: 0 10px;
        transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
        width: 100%;
        box-sizing: border-box;
      }

      .one-selected:focus {
        border: 1px solid rgba(75, 110, 239, 1);
        box-shadow: 0 0 0 2px rgba(75, 110, 239, 0.3);
      }

      /* 验证错误 */
      .register .layui-form-danger.layui-input:focus {
        border-color: #ff5722 !important;
        box-shadow: none;
      }

      /* 下拉内容 */
      .select-item-box {
        position: absolute;
        top: 100%;
        width: 100%;
        max-height: 150px;
        border: 1px solid #e4e7ed;
        border-radius: 4px;
        background-color: #fff;
        box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
        box-sizing: border-box;
        margin: 5px 0px;
        overflow: hidden;
        overflow-y: auto;
        padding: 8px 12px;
        z-index: 100;
        display: none;
        font-size: 14px;
        line-height: 34px;
        font-weight: 400;
      }

      .select-change {
        width: 20px !important;
      }

      .select-change::before {
        display: inline-block;
        transition: transform 0.2s;
        transform: rotate(0deg);
      }

      .select-change-open::before {
        transform: rotate(-90deg);
      }

      /* 滚动条 start */
      ::-webkit-scrollbar {
        width: 8px;
      }

      ::-webkit-scrollbar-thumb {
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 8px rgba(144, 147, 153, 0.3);
        background: rgba(144, 147, 153, 0.3);
        /*颜色*/
      }

      ::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 8px rgba(144, 147, 153, 0.3);
        background: #ffffff;
      }
      /* 滚动条 end */

      .select-item {
        cursor: pointer;
      }

      .inner-child-item {
        padding-left: 20px;
        box-sizing: border-box;
      }

      .hash-child-item {
        padding-left: 26px;
        position: relative;
      }

      .single-item {
        padding-left: 8px;
      }

      .hash-child-item:hover,
      .single-item:hover {
        background: #edf0fd;
        color: #4b6eef;
        border-radius: 2px;
      }

      .hash-child-item .layui-icon-down {
        position: absolute;
        left: 8px;
        top: 0;
        font-size: 12px;
      }

      .layui-input-block .layui-icon-down.select-icon {
        top: 9px;
      }

      /* 空数据 */
      .no-list {
        font-family: SourceHanSansCN-Regular;
        height: 42px;
        line-height: 42px;
        text-align: center;
        font-size: 14px;
        color: #bfbfbf;
      }

      .top-list {
        height: 26px;
        line-height: 26px;
      }
    </style>
    <script src="res/js/qwebchannel.js"></script>
    <script src="res/layui/layui.js"></script>
    <script src="res/js/contextMenu.js"></script>
    <script>
      layui.use(function () {
        let $ = layui.$;
        let form = layui.form;
        let util = layui.util;
        let dropdown = layui.dropdown; // 下拉菜单组件
        let deptDropdown = null;
        let userDropdown = null;
        let submitData = {};
        let DepartID = null;
        let layer = layui.layer;

        // 判断客户端类型 默认值是什么
        let clientType = sessionStorage.getItem("clientType") || "Online";

        // 清除cdkey告警提示
        $("#cdkey-input").on("input", function (e) {
          console.log(e.delegateTarget.value);
          if (!e.delegateTarget.value) {
            $(".error-info").hide(200, "linear");
          }
        });

        // 验证授权文件
        form.verify({
          cdkey: function (value, item) {
            if (!value) {
              $(".error-text").text("请输入激活码");
              $(".error-info").show(200, "linear");
              setTimeout(() => {
                $(".error-info").hide(200, "linear");
              }, 2000);
              return true;
            }
          },
        });

        // 区分环境
        function checkClientType(resClientType) {
          clientType = resClientType;
          if (resClientType === "Online") {
            $(".offline-item").remove(); // 移除离线客户端部分的dom
            let deptDom = `
            <input class="one-selected layui-input" name="DepartID" type="text" id="dept-select" lay-verify="required"
              placeholder="请选择部门" maxlength="0" autocomplete="off" />
            <i class="select-icon layui-icon layui-icon-down"></i>
            <div class="select-item-box">
              <div class='no-list top-list'>暂无数据</div>
            </div>`; // 部门select树
            $(".one-tree-select").html(deptDom);
            getDeptList(); // 获取部门树

            let userDom = `
          <input class="layui-input" name="UserID" type="text" id="person-select" lay-verify="required"
            placeholder="请选择责任人" autocomplete="off" />
          <i class="layui-icon layui-icon-down"></i>`; // 负责人select树
            $(".user-input-part").html(userDom);

            $(".register").addClass("online-type"); // 添加类名 切换对应布局
            renderUserList([]); // 初始化用户select

            // TODO本地测试
            // let res = JSON.parse('{"body":{"ret":"0","list":[{"id":"1","name":"测试单位","pid":"0"},{"id":"1027269597205626880","name":"测试部门","pid":"1"},{"id":"1027522824815771648","name":"测试级单位","pid":"1"},{"id":"1032606503053295616","name":"二级部门","pid":"1027269597205626880"},{"id":"1042382656131563520","name":"三级部1","pid":"1032606503053295616"}]},"cmd":"res_get_depts"}')
            // let data = arrayToTree(res.body.list)
            // let treedom = creatTreePart(data)
            // if (data.length <= 0) {
            //   treedom = "<div class='no-list top-list'>暂无数据</div>"
            // }
            // $('.select-item-box').html(treedom)
          }
        }
        // 注册激活 结果 离线
        function redeemResult(res) {
          if (res.Ret !== "0") {
            $(".error-text").text(res.Desc);
            $(".error-info").show(200, "linear");
          }
        }
        // 数据接收函数
        var SignalJsResponse = function (json) {
          if (!json) {
            return;
          }
          let cmdType = JSON.parse(json).cmd || ""; // 请求的内容
          let res = JSON.parse(json) || {};
          switch (cmdType) {
            case "res_get_depts": //组织机构
              let data = arrayToTree(res.body.list);
              let treedom = creatTreePart(data);
              if (data.length <= 0) {
                treedom = "<div class='no-list top-list'>暂无数据</div>";
              }
              $(".select-item-box").html(treedom);
              break;
            case "ClientTypeRes": // 客户端类型
              checkClientType(res.ClientType);
              $("#deviceId").text(res.ShowAuthorCode);
              break;
            // 负责人
            case "res_get_users":
              setUserList(res);
              break;
            case "RegisterRes": // 注册激活状态 离线版
              redeemResult(res);
              break;
          }
        };

        // 创建树状下拉内容
        function creatTreePart(arr) {
          let html = "";
          for (let item of arr) {
            html += item.child
              ? `
              <div class='hash-child-item-box'>
                <div class='hash-child-item select-item' data-id=${
                  item.id
                }><i class="layui-icon layui-icon-down select-change"></i><span>${
                  item.title
                }</span></div>
                <div class='inner-child-item'>${creatTreePart(item.child)}</div>
              </div>  
              `
              : `<div class='single-item select-item' data-id=${item.id}>${item.title}</div>`;
          }
          return html;
        }

        //展开 收缩下拉框
        $(document).on("click", ".one-tree-select", function () {
          $(this).find(".select-item-box").toggle();
        });
        // 点击事件 排除树状结构收缩部分
        $(".register").click(function (e) {
          let className = e.target.className;
          // 排除展开收缩图标 点击
          if (className.indexOf("select-change") < 0) {
            $(".select-item-box").hide();
          }
        });

        //禁止触发父级事件
        $(document).on("click", ".select-item-box", function (e) {
          e.stopPropagation();
        });
        //点击下拉框 选中该下拉框的值
        $(document).on("click", ".select-item", function (e) {
          e.stopPropagation();
          console.log(".select-item");
          let title = $(this)[0].innerText;
          let id = $(this)[0].dataset.id;

          getUserList(id); // 获取负责人
          $("#dept-select").attr("value", title);
          submitData.DepartID = id;

          $("#person-select").val("");
          submitData.UserID = "";

          $(".select-item-box").hide();
        });
        //点击展开符 隐藏 展开子级
        $(document).on("click", ".select-change", function (e) {
          e.stopPropagation();
          $(this)
            .parents(".hash-child-item")
            .nextAll(".inner-child-item")
            .toggle();
          if ($(this).hasClass("select-change-open")) {
            $(this).removeClass("select-change-open");
          } else {
            $(this).addClass("select-change-open");
          }
        });

        // js与c++请求调用
        new QWebChannel(qt.webChannelTransport, function (channel) {
          var webobj = channel.objects.reg_dlg_object;
          window.reg_dlg = webobj;
          window.reg_dlg.SignalJsResponse.connect(SignalJsResponse);
          // 数据发送函数
          window.reqPageData = function (data) {
            let reqData = JSON.stringify(data);
            reg_dlg.SlotJsRequest(reqData);
          };
        });

        setTimeout(() => {
          getClientType();
        });

        // 获取 在线离线 ClientType
        function getClientType() {
          let data = {
            cmd: "ClientTypeReq",
          };
          reqPageData(data);
        }

        // 获取部门树
        function getDeptList() {
          let data = {
            cmd: "req_get_depts",
            body: {
              pid: "",
            },
          };
          reqPageData(data);
        }
        // 获取负责人列表
        function getUserList(id) {
          let data = {
            cmd: "req_get_users",
            body: {
              dept_id: id,
            },
          };
          reqPageData(data);
        }
        // 负责人 数据渲染
        function setUserList(res) {
          let arr = res.body.list || [];
          let newDropDown = [];
          arr.forEach((item) => {
            newDropDown.push({
              id: item.id,
              title: item.name,
            });
          });
          userDropdown.reload({ data: newDropDown });
        }

        // TODO 测试
        // let res = '{"body":{"ret":"0","dept_id":"0","list":[{"id":"1040277347527294976","name":"smanager"},{"id":"1048687235588685824","name":"宏宇_windows"},{"id":"1049307020106137600","name":"牧也"}]},"cmd":"res_get_users"}'
        // setTimeout(() => {
        //   setUserList(JSON.parse(res))
        // }, 2000)

        // 责任人 输入框监听
        $("#person-select").bind("input propertychange ", function () {
          submitData.UserID = null;
        });

        // 注册保存 离线
        function saveData() {
          let UserName = $("#person-select").val() || "";
          let DepartName = $("#dept-select").val() || "";
          let UserID = submitData.UserID || "";
          let DepartID = submitData.DepartID || "";
          let data = {
            cmd: "RegisterReq",
            DepartID: DepartID,
            DepartName: DepartName,
            UserID: "", // 用户ID(如果不是选择的，是填写的为'')
            UserName: UserName,
            AuthorCode: $("#cdkey-input").val() || "", // 激活码
          };
          reqPageData(data);
        }
        // 注册保存 在线 Online
        function saveDataOnline() {
          let UserName = $("#person-select").val() || "";
          let UserID = submitData.UserID || "";
          let DepartID = submitData.DepartID || "";
          let data = {
            cmd: "req_reg",
            body: {
              dev_name: "",
              mac: "",
              ip: "",
              hdsn: "",
              os_type: "",
              os_ver: "",
              dept_id: DepartID,
              uid: UserID, // 用户ID(如果不是选择的，是填写的为'')
              uname: UserName, // 用户名(选择或者填写)
            },
          };
          if (UserName && !UserID) {
            // 用户名 为手动输入
            data.body.uid = "";
          }
          reqPageData(data);
        }
        // 渲染责任人select
        function renderUserList(data) {
          userDropdown = dropdown.render({
            elem: "#person-select",
            style:
              "width: 240px;max-height: 100px;overflow-x:hidden;overflow-y:auto;",
            data: data,
            id: "person-select",
            click: function (data, othis) {
              $("#person-select").val(data.title);
              submitData.UserID = data.id;
            },
          });
        }

        // 树结构
        function arrayToTree(data) {
          let result = [];
          if (!Array.isArray(data)) {
            return result;
          }
          data.forEach((item) => {
            item.id = item.id;
            item.title = item.name;
            delete item.child;
          }); // 变量对应
          let map = {};
          data.forEach((item) => {
            map[item.id] = item; // 对应id 提取所有对象
          });
          data.forEach((item) => {
            let parent = map[item.pid]; // 根据pid 找到对应id与pid相同的 对象
            if (parent) {
              parent.type = "group";
              (parent.child || (parent.child = [])).push(item); // 父级没有child，赋予空的child数组，并将子集对象存入
            } else {
              result.push(item); // 根
            }
          });
          return result;
        }

        //提交
        form.on("submit(formSubmit)", function (data) {
          // 离线版 在线版 区分
          if (clientType === "Online") {
            saveDataOnline();
          } else {
            saveData();
          }
          return false;
        });
      });
    </script>
  </head>

  <body>
    <!-- c++弹框头部 -->
    <div class="popup-header"></div>
    <div class="register">
      <!-- 默认为离线版布局 -->
      <form class="layui-form">
        <div class="layui-form-item offline-item">
          <label class="layui-form-label">机器码：</label>
          <div class="layui-input-block">
            <span id="deviceId">- - - - - - - - - -</span>
          </div>
        </div>
        <div class="layui-form-item offline-item">
          <label class="layui-form-label layui-form-label-require"
            >激活码：</label
          >
          <div class="layui-input-block upload-block">
            <label for="fileUpload">
              <div class="upload-part">
                <input
                  class="layui-input"
                  name="cdkey"
                  type="text"
                  id="cdkey-input"
                  lay-verify="cdkey"
                  placeholder="请输入激活码"
                  autocomplete="off"
                />
              </div>
            </label>
            <!-- 错误信息 -->
            <div class="error-info">
              <span class="error-key">
                <img
                  class="icon"
                  src="res/img/errorIcon.png"
                  alt=""
                  srcset=""
                />
                <span class="error-text">激活码不匹配，请重新输入</span>
              </span>
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">单位/部门：</label>
          <div class="layui-input-block" id="dept">
            <div class="one-tree-select">
              <input
                class="one-selected layui-input"
                name="DepartID"
                type="text"
                id="dept-select"
                lay-verify="required"
                placeholder="请输入部门"
                autocomplete="off"
              />
            </div>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">责任人：</label>
          <div class="layui-input-block user-input-part">
            <input
              class="layui-input"
              name="UserID"
              type="text"
              id="person-select"
              lay-verify="required"
              placeholder="请输入责任人"
              autocomplete="off"
            />
          </div>
        </div>
        <div class="layui-form-item submit-item">
          <div class="submit-box">
            <button
              type="text"
              class="layui-btn"
              lay-submit
              lay-filter="formSubmit"
            >
              注册
            </button>
          </div>
        </div>
      </form>
    </div>
  </body>
</html>
